package com.laoxu.java.io;

import com.laoxu.java.entity.Employee;
import com.laoxu.java.entity.Manager;

import java.io.*;
import java.text.SimpleDateFormat;

/**
 * @Description: 对象序列化例子
 * @Author laoxu
 * @Date 2020/10/31 10:33
 **/
public class ObjectSerializeDemo {
    public static void main(String[] args) {
        String saveFilePath = "D:/backup/staff.dat";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Employee harry = new Employee("Harry", 5000, "1999-12-20" );
        Manager carl = new Manager("Carl", 20000, "1989-11-30");
        carl.setSecretary(harry);
        Manager tony = new Manager("Tony", 40000, "1990-01-02");
        tony.setSecretary(harry);

        Employee[] staff = new Employee[3];
        staff[0] = carl;
        staff[1] = harry;
        staff[2] = tony;

        // 将staff写出到文件
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(saveFilePath));
            out.writeObject(staff);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        // 从文件读取staff
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(saveFilePath));
            try {
                Employee[] newStaff = (Employee[]) in.readObject();
                in.close();
                // 给秘书加工资
                newStaff[1].raiseSalary(100);
                for (Employee e: newStaff) {
                    System.out.println(e);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
